#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
using namespace std;

//在上锁间抛异常导致死锁
condition_variable cv;
mutex mx;
int x = 0;
void threadFunc1(int& n,condition_variable& cv)
{
    srand(time(nullptr));
    try
    {
        for (int i = 1;i <= n;i++)
        {
            mx.lock();
            int num = rand() % 2;
            if (num)
                cout << "t1 print：" << num << "  x is：" << x++ << endl;
            else
                throw invalid_argument("异常！");
            mx.unlock();
        }
    }
    catch(const exception& e)
    {
        cout << e.what() << endl;
    }
}
void threadFunc2(int& n,mutex& mx,condition_variable& cv)
{
    for (int i = 1;i <= n;++i)
    {
        mx.lock();
        cout << "t2 print:" << i << "  x is:" << x++ << endl;
        mx.unlock();
    }
}

int main()
{
//    char c;
//   /* c = getchar();
//    putchar(c);*/
//    scanf_s("%c", &c);
//    cout << c;
    int n = 5;
    /*try 
    {
        thread t1(threadFunc1, ref(n), ref(cv));
    }*/
    thread t1(threadFunc1, ref(n), ref(cv));
    t1.join(); //主线程阻塞，无法实例化t2，让因此t1先执行，t2后执行

    thread t2(threadFunc2, ref(n), ref(mx), ref(cv)); //如果mx和cv定义为是在全局定义的，如果要在函数中调用不用给函数传，直接使用全局变量即可
    t2.join();
    return 0;
}